package com.huike.report.service.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import com.huike.clues.mapper.SysDictDataMapper;
import com.huike.contract.domain.TbContract;
import com.huike.contract.domain.vo.BusinesschangeVO;
import com.huike.contract.mapper.TbContractMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.huike.clues.domain.Report;
import com.huike.clues.domain.dto.ReportDto;
import com.huike.clues.domain.vo.ClueReportVo;
import com.huike.clues.domain.vo.ReportVo;
import com.huike.common.core.page.TableDataInfo;
import com.huike.report.domain.DTO.PageDTO;
import com.huike.report.domain.page.PageReport;
import com.huike.report.domain.vo.*;
import com.huike.report.mapper.ReportMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.huike.clues.mapper.SysDeptMapper;
import com.huike.report.service.IReportService;

@Service
public class ReportServiceImpl implements IReportService {
    @Autowired
    private TbContractMapper contractMapper;
    @Autowired
    private ReportMapper reportMapper;

 /*   @Autowired
    private ReportMapper reportMapper;*/

    @Autowired
    private SysDictDataMapper sysDictDataMapper;
    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Autowired
    private TbContractMapper tbContractMapper;


    /**
     * *************看我看我**************
     * 传入两个时间范围，返回这两个时间范围内的所有时间，并保存在一个集合中
     *
     * @param beginTime
     * @param endCreatTime
     * @return
     * @throws ParseException
     */
    public static List<String> findDates(String beginTime, String endCreatTime)
            throws ParseException {
        List<String> allDate = new ArrayList();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Date dBegin = sdf.parse(beginTime);
        Date dEnd = sdf.parse(endCreatTime);
        allDate.add(sdf.format(dBegin));
        Calendar calBegin = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calBegin.setTime(dBegin);
        Calendar calEnd = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calEnd.setTime(dEnd);
        // 测试此日期是否在指定日期之后
        while (dEnd.after(calBegin.getTime())) {
            // 根据日历的规则，为给定的日历字段添加或减去指定的时间量
            calBegin.add(Calendar.DAY_OF_MONTH, 1);
            allDate.add(sdf.format(calBegin.getTime()));
        }
        System.out.println("时间==" + allDate);
        return allDate;
    }


    /**
     * ************看我看我***********
     * 用我能少走很多路
     * 我是用来机选百分比的方法
     *
     * @param all
     * @param num
     * @return
     */
    private BigDecimal getRadio(Integer all, Integer num) {
        if (all.intValue() == 0) {
            return new BigDecimal(0);
        }
        BigDecimal numBigDecimal = new BigDecimal(num);
        BigDecimal allBigDecimal = new BigDecimal(all);
        BigDecimal divide = numBigDecimal.divide(allBigDecimal, 4, BigDecimal.ROUND_HALF_UP);
        return divide.multiply(new BigDecimal(100));
    }
    @Override
    public LineChartVO contractStatistics(String beginCreateTime, String endCreateTime) throws ParseException {
        //创建对象
        LineChartVO lineChartVo =new LineChartVO();

            List<String> timeList = findDates(beginCreateTime, endCreateTime);
            //创建时间集合 x轴
            lineChartVo.setxAxis(timeList);
            //定义返回值集合
            List<LineSeriesVO> list = new ArrayList<>();
            //创建新增客户和总客户的集合
            LineSeriesVO lineSeries1 = new LineSeriesVO();
            LineSeriesVO lineSeries2 = new LineSeriesVO();
            //查询每一天的客户数量
            List<Map<String, Object>> statics = contractMapper.contractStatistics(beginCreateTime, endCreateTime);
            //定义客户总数一个初始值
            int sum = 0;
            //遍历时间集合
            for (String s : timeList) {
                //流的方法过滤查找合适的元素和接收
                Optional<Map<String, Object>> optional = statics.stream().filter(d -> d.get("dd").equals(s)).findFirst();
                //判断查找的元素是否存在
                if (optional.isPresent()) {
                    //进行添加
                    Map<String, Object> currentData = optional.get();
                    lineSeries1.getData().add(currentData.get("num"));
                    sum += Integer.parseInt(currentData.get("num").toString());//可以获取到这个值并通过 toString() 将其转换为字符串类型。然后转化为整数类型
                } else {
                    //如果为零 则相加为0
                    lineSeries1.getData().add(0);
                }
                //总客户数+1
                lineSeries2.getData().add(sum);
            }
            list.add(lineSeries1);
            list.add(lineSeries2);
            lineChartVo.setSeries(list);
            return lineChartVo;
        }

    @Override
    public  List<Map<String, Object>> subjectStatistics(String beginCreateTime, String endCreateTime) {
        List<Map<String, Object>> data= contractMapper.subjectStatistics(beginCreateTime,endCreateTime);
        for (Map<String, Object> datum : data) {
            String subjectValue= (String) datum.get("subject");
            String lable=  sysDictDataMapper.selectDictLabel("course_subject",subjectValue);
            datum.put("subject",lable);
        }
        return data;
    }
    @Override
    public List<TbContract> contractReportList(TbContract tbContract) {
        return contractMapper.selectTbContractList(tbContract);
    }

    @Override
    public List<ActivityStatisTicVO> activityStatisTice(LocalDate beginCreateTime, LocalDate endCreateTime) {
        ArrayList<ActivityStatisTicVO> activityStatisTicVOS = new ArrayList<>();
        List<ActivityStatisTicVO> activityStatisTicVOS1 = reportMapper.activityStatisTice(beginCreateTime, endCreateTime);
        for (ActivityStatisTicVO ticVO : activityStatisTicVOS1) {
            ActivityStatisTicVO activityStatisTicVO = new ActivityStatisTicVO();
            BeanUtils.copyProperties(ticVO,activityStatisTicVO);
            Long activityId = ticVO.getActivityId();
            Integer num = reportMapper.clueById(activityId);
            activityStatisTicVO.  setNum(num);
            activityStatisTicVOS.add(activityStatisTicVO);
        }
        return activityStatisTicVOS;
    }


    @Override
    public VulnerabilityMapVo getVulnerabilityMap(LocalDate beginCreateTime, LocalDate endCreateTime) {
        VulnerabilityMapVo vulnerabilityMapVo = new VulnerabilityMapVo();
        LocalDateTime beginDate = LocalDateTime.of(beginCreateTime, LocalTime.MIN);
        LocalDateTime endDate = LocalDateTime.of(endCreateTime, LocalTime.MAX);
        HashMap<String, Object> map = new HashMap<>();
        map.put("beginDate", beginDate);
        map.put("endDate", endDate);
        Integer cluesNums = reportMapper.cluesNum(map);
        Integer effectiveCluesNums = reportMapper.businessNum(map);
        Integer businessNums = reportMapper.businessNum(map);
        Integer contractNums = reportMapper.contractNum(map);
        vulnerabilityMapVo.setCluesNums(cluesNums);
        vulnerabilityMapVo.setEffectiveCluesNums(effectiveCluesNums);
        vulnerabilityMapVo.setBusinessNums(businessNums);
        vulnerabilityMapVo.setContractNums(contractNums);


        return vulnerabilityMapVo;
    }



    @Override
    public LineChartVO salesStatistics(String beginCreateTime, String endCreateTime) {
        LineChartVO lineChartVO = new LineChartVO();

        try {
            List<String> dates = findDates(beginCreateTime, endCreateTime);
            lineChartVO.setxAxis(dates);
            ArrayList<LineSeriesVO> lineSeriesVOS = new ArrayList<>();
            List<Map<String, Object>> statistics = tbContractMapper.salesStatistics(beginCreateTime, endCreateTime);
            LineSeriesVO lineSeriesVO = new LineSeriesVO();
            lineSeriesVO.setName("新增学员");
            LineSeriesVO lineSeriesVO1 = new LineSeriesVO();
            lineSeriesVO1.setName("学员总数");
//            int sum = 0;
            for (String s : dates) {
                Optional optional = statistics.stream().filter(d -> d.get("dd").equals(s)).findFirst();
                if (optional.isPresent()) {
                    Map<String, Object> map = (Map<String, Object>) optional.get();
                    lineSeriesVO.getData().add(map.get("num"));
//                    sum += Integer.parseInt(map.get("num").toString());
                } else {
                    lineSeriesVO.getData().add(0);
                }
            }
            lineSeriesVOS.add(lineSeriesVO);
            lineChartVO.setSeries(lineSeriesVOS);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return lineChartVO;
    }

    @Override
    public List<Map<String, Object>> deptStatisticsList(String beginCreateTime, String endCreateTime) {
        List<Map<String, Object>> data = tbContractMapper.deptStatistics(beginCreateTime, endCreateTime);
       /* for (Map<String, Object> datum : data) {
            Long deptId = (Long) datum.get("dept_id");
            if (deptId != null) {
                SysDept sysDept = sysDeptMapper.selectDeptById(deptId);
                datum.put("deptName", sysDept.getDeptName());
            }
        }*/
        return data;
    }

    @Override
    public List<Map<String, Object>> ownerShipStatisticsList(String beginCreateTime, String endCreateTime) {
       return tbContractMapper.ownerShipStatisticsList(beginCreateTime,endCreateTime);
    }


    @Override
    public List<Map<String, Object>> channelStatisticsList(String beginCreateTime, String endCreateTime) {

        List<Map<String, Object>> data = tbContractMapper.channelStatisticsList(beginCreateTime, endCreateTime);
        for (Map<String, Object> datum : data) {
            String subjectValue = (String) datum.get("channel");
            if (subjectValue != null) {
                String lable = sysDictDataMapper.selectDictLabel("clues_item", subjectValue);
                datum.put("channel", lable);
            }
        }
        return data;
    }




    @Override
    public TableDataInfo page(ReportDto reportDto) {
        // 分页显示
        PageHelper.startPage(reportDto.getPageNum(), reportDto.getPageSize());
        Page<ClueReportVo> page = reportMapper.page(reportDto);
        List<ClueReportVo> result = page.getResult();

        // 组装TableDataInfo返回
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setTotal(page.getTotal());
        tableDataInfo.setParams(null);
        tableDataInfo.setCode(200);
        tableDataInfo.setMsg("响应成功");
        tableDataInfo.setRows(result);
        return tableDataInfo;
    }

    @Override
    public PageReport actPage(PageDTO pageDTO) {
        PageHelper.startPage(pageDTO.getPageNum(),pageDTO.getPageSize());


        Page<ActivityStatisticsVo> page =reportMapper.actPage(pageDTO);

        List<ActivityStatisticsVo> result = page.getResult();
        PageReport pageReport = new PageReport();
        ArrayList<ActivityStatisticsVo> activityStatisticsVos = new ArrayList<>();
        for (ActivityStatisticsVo vo : result) {
            Long activityByid = vo.getId();
            ActivityStatisticsVo activityStatisticsVo = new ActivityStatisticsVo();
            BeanUtils.copyProperties(vo,activityStatisticsVo);
            Integer cluesNum=reportMapper.clueactivityById(activityByid);
            if (cluesNum==null){cluesNum=0;}
            Integer falseCluesNum=reportMapper.falseClues(activityByid);
            if (falseCluesNum==null){falseCluesNum=0;}
            Integer businessNum=reportMapper.businessNumById(activityByid);
            if (businessNum==null){businessNum=0;}
            Integer customersNum=reportMapper.customersNumById(activityByid);
            if (customersNum==null){customersNum=0;}
            activityStatisticsVo.setCluesNum(cluesNum);
            activityStatisticsVo.setFalseCluesNum(falseCluesNum);
            activityStatisticsVo.setBusinessNum(businessNum);
            activityStatisticsVo.setCustomersNum(customersNum);

            Double amount=reportMapper.amount(activityByid);//订单价格
            if (amount==null){amount=0.0;}
            Double cost=reportMapper.cost(activityByid);//原价
            if (cost==null){cost=0.0;}
            activityStatisticsVo.setAmount(amount);
            activityStatisticsVo.setCost(cost-amount );
            activityStatisticsVos.add(activityStatisticsVo);
        }
        pageReport.setRows(activityStatisticsVos);
        pageReport.setTotal(page.getTotal());
        pageReport.setCode(200);
        pageReport.setMsg("查询成功");
        return pageReport;
    }

        @Override
        public ReportVo getCluesStatistics(ReportDto reportDto) {
            // 调用提供方法获得时间集合
            LocalDate beginCreateTime = reportDto.getBeginCreateTime();//开始时间
            LocalDate endCreateTime = reportDto.getEndCreateTime();//结束时间
            // 捕获异常 不知道为什么
            List<String> dates = new ArrayList<>();//时间集合

            ArrayList<Integer> newUserList = new ArrayList<>();//新增集合
            ArrayList<Integer> totalUserList = new ArrayList<>();//总用户集合
            try {
                dates = findDates(beginCreateTime.toString(), endCreateTime.toString());
                //获得集合数据
                for (String date : dates) {
                    LocalDate parse = LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                    LocalDateTime beginTime = LocalDateTime.of(parse, LocalTime.MIN);
                    LocalDateTime endTime = LocalDateTime.of(parse, LocalTime.MAX);
                    //准备查询数据
                    HashMap<String, Object> map = new HashMap<>();

                    map.put("endTime", endTime);
                    Integer totalUser = reportMapper.userStatistics(map);

                    map.put("beginTime", beginTime);
                    Integer newUser = reportMapper.userStatistics(map);

                    newUserList.add(newUser);
                    totalUserList.add(totalUser);
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
            // 准备Series数据
            ArrayList<Report> reports = new ArrayList<>();
            Report report = new Report();
            report.setName("新增客户数");
            report.setData(newUserList);
            Report report1 = new Report();
            report1.setName("客户总数");
            report1.setData(totalUserList);
            reports.add(report);
            reports.add(report1);

            // 返回数据准备
            ReportVo reportVo = new ReportVo();
            reportVo.setXAxis(dates);//时间数据 传入时间类型集合
            reportVo.setSeries(reports);//条数数据准备 传入report类型集合
            return reportVo;
        }


    @Override
    public List<ChanelStatisticsVo> chanelStatistics(LocalDate beginCreateTime, LocalDate endCreateTime) {
        List<ChanelStatisticsVo> chanelStatisticsVos = reportMapper.chanelStatistics(beginCreateTime, endCreateTime);
        for (ChanelStatisticsVo vo : chanelStatisticsVos) {
            String channel = vo.getChannel();
            if (channel == null) {
                vo.setChannel("其他");
            } else {
                String channelName = reportMapper.onlineType(channel);
                vo.setChannel(channelName);
            }

            // chanelStatisticsVos.add(vo);
        }
        return chanelStatisticsVos;
    }
    /**
     * 线索转换龙虎榜
     * @param beginCreateTime
     * @param endCreateTime
     * @param deptId
     * @return
     */
    @Override
    public List<BusinesschangeVO> salesStatistic(String beginCreateTime, String endCreateTime, Long deptId) {
        // 获取时间段的 总数量
        int all = reportMapper.getclue(beginCreateTime, endCreateTime);

        List<BusinesschangeVO> volist = reportMapper.getVOlist(beginCreateTime, endCreateTime);
        List<BusinesschangeVO> collect = volist.stream().map(vo -> {
            vo.setRadio(getRadio(all, vo.getNum()));
            return vo;
        }).collect(Collectors.toList());
        return collect;
    }
    /**
     *商机转换龙虎榜
     * @param beginCreateTime
     * @param endCreateTime
     * @param deptId
     * @return
     */
    @Override
    public List<BusinesschangeVO> businessChangeStatistics(String beginCreateTime, String endCreateTime, Long deptId) {
        //统计num 商机转换套数
        Integer num = reportMapper.getById(beginCreateTime, endCreateTime);
        List<BusinesschangeVO> list = reportMapper.getlist(beginCreateTime,endCreateTime);
        list.stream().map(businesschangeVO -> {
            // 计算转换率
            businesschangeVO.setCreate_by(businesschangeVO.getCreate_by());
            businesschangeVO.setRadio(getRadio(num, businesschangeVO.getNum()));
            return businesschangeVO;
        }).collect(Collectors.toList());
        return list;
    }


}

